package cn.wolfcode.rbac.web.interceptor;

import cn.wolfcode.rbac.utils.RedisUtils;
import cn.wolfcode.rbac.utils.R;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static cn.wolfcode.rbac.common.RedisKeyPrefix.LOGIN_EMPLOYEE_PREFIX;

/**
 * 登录拦截器
 */
@Component
public class CheckLoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisUtils redisUtils;

    /*
    handler是拦截请求的Controller类对象,但是如果要获取Controller类中的方法,要进行强转为 HandlerMethod
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果请求不是handlerMethod的请求，则是预请求，预请求是看该请求是否支持跨域,预请求则放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        response.setContentType("application/json;charset=utf-8");
        //获取请求头中用户id
        String userId = request.getHeader("userId");
        //从redis中获取用户信息,判断是否有登录
        String obj = redisUtils.get(LOGIN_EMPLOYEE_PREFIX + userId);
        // 没有登录则不放行并且响应401
        if (StringUtils.isEmpty(obj)) {
            response.getWriter().write(JSON.toJSONString(R.fail(401, "验证失败")));
            return false;
        }
        // 有登录则放行
        return true;
    }
}
